<template>
  <div class="code-block-wrapper" :data-language="language">
    <!-- 代码块头部 -->
    <div class="code-header">
      <div class="language-info">
        <div class="language-badge" :class="`lang-${language}`">
          <i :class="getLanguageIcon(language)"></i>
          <span>{{ getLanguageDisplayName(language) }}</span>
        </div>
        <div class="code-meta" v-if="showLineCount">
          <span class="line-count">{{ lineCount }} 行</span>
        </div>
      </div>
      
      <div class="code-actions">
        <button 
          v-if="language === 'html'"
          class="action-btn run-btn"
          @click="runCode"
          :disabled="isRunning"
          :title="'运行HTML代码'"
        >
          <i class="fas fa-play" v-if="!isRunning"></i>
          <i class="fas fa-spinner fa-spin" v-else></i>
          <span>{{ isRunning ? '运行中...' : '运行' }}</span>
        </button>
        
        <button 
          class="action-btn copy-btn"
          @click="copyCode"
          :disabled="isCopying"
          :title="'复制代码'"
        >
          <i class="fas fa-copy" v-if="!isCopying && !justCopied"></i>
          <i class="fas fa-check" v-else-if="justCopied"></i>
          <i class="fas fa-spinner fa-spin" v-else></i>
          <span>{{ getCopyButtonText() }}</span>
        </button>
        
        <button 
          class="action-btn expand-btn"
          @click="toggleExpanded"
          v-if="showExpandButton"
          :title="isExpanded ? '收起代码' : '展开代码'"
        >
          <i :class="isExpanded ? 'fas fa-compress' : 'fas fa-expand'"></i>
        </button>
      </div>
    </div>
    
    <!-- 代码内容 -->
    <div 
      class="code-content" 
      :class="{ 
        'expanded': isExpanded,
        'collapsible': showExpandButton,
        'line-numbers': showLineNumbers
      }"
    >
      <pre 
        class="code-pre"
        :class="{ 'line-numbers': showLineNumbers }"
      ><code 
        :class="`language-${language}`"
        v-html="highlightedCode"
      ></code></pre>
      
      <!-- 代码行号 -->
      <div v-if="showLineNumbers" class="line-numbers-container">
        <span 
          v-for="n in lineCount" 
          :key="n" 
          class="line-number"
          :class="{ 'highlighted': highlightedLines.includes(n) }"
        >
          {{ n }}
        </span>
      </div>
    </div>
    
    <!-- 展开提示 -->
    <div v-if="showExpandButton && !isExpanded" class="expand-hint">
      <button class="expand-hint-btn" @click="toggleExpanded">
        <i class="fas fa-chevron-down"></i>
        <span>点击展开查看完整代码 ({{ lineCount }} 行)</span>
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import Prism from 'prismjs'

const props = defineProps({
  code: {
    type: String,
    required: true
  },
  language: {
    type: String,
    default: 'text'
  },
  showLineNumbers: {
    type: Boolean,
    default: true
  },
  showLineCount: {
    type: Boolean,
    default: true
  },
  maxHeight: {
    type: String,
    default: '400px'
  },
  highlightedLines: {
    type: Array,
    default: () => []
  },
  filename: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['run-code'])

// 响应式状态
const isCopying = ref(false)
const justCopied = ref(false)
const isRunning = ref(false)
const isExpanded = ref(false)

// 计算属性
const lineCount = computed(() => {
  return props.code.split('\n').length
})

const showExpandButton = computed(() => {
  return lineCount.value > 15 // 超过15行显示展开按钮
})

const highlightedCode = computed(() => {
  const lang = props.language && Prism.languages[props.language] ? props.language : 'clike'
  try {
    return Prism.highlight(props.code, Prism.languages[lang], lang)
  } catch (error) {
    console.warn('代码高亮失败:', error)
    return props.code
  }
})

// 语言相关工具函数
const getLanguageIcon = (lang) => {
  const iconMap = {
    javascript: 'fab fa-js-square',
    typescript: 'fab fa-js-square',
    html: 'fab fa-html5',
    css: 'fab fa-css3-alt',
    java: 'fab fa-java',
    python: 'fab fa-python',
    php: 'fab fa-php',
    vue: 'fab fa-vuejs',
    react: 'fab fa-react',
    angular: 'fab fa-angular',
    node: 'fab fa-node-js',
    sql: 'fas fa-database',
    json: 'fas fa-code',
    xml: 'fas fa-code',
    yaml: 'fas fa-code',
    markdown: 'fab fa-markdown',
    bash: 'fas fa-terminal',
    shell: 'fas fa-terminal',
    powershell: 'fas fa-terminal',
    docker: 'fab fa-docker',
    git: 'fab fa-git-alt'
  }
  return iconMap[lang] || 'fas fa-code'
}

const getLanguageDisplayName = (lang) => {
  const nameMap = {
    javascript: 'JavaScript',
    typescript: 'TypeScript',
    html: 'HTML',
    css: 'CSS',
    java: 'Java',
    python: 'Python',
    php: 'PHP',
    vue: 'Vue',
    react: 'React',
    angular: 'Angular',
    node: 'Node.js',
    sql: 'SQL',
    json: 'JSON',
    xml: 'XML',
    yaml: 'YAML',
    markdown: 'Markdown',
    bash: 'Bash',
    shell: 'Shell',
    powershell: 'PowerShell',
    docker: 'Docker',
    git: 'Git',
    clike: 'Code'
  }
  return nameMap[lang] || lang.toUpperCase()
}

// 复制功能
const getCopyButtonText = () => {
  if (isCopying.value) return '复制中...'
  if (justCopied.value) return '已复制'
  return '复制'
}

const copyCode = async () => {
  if (isCopying.value) return
  
  isCopying.value = true
  
  try {
    await navigator.clipboard.writeText(props.code)
    justCopied.value = true
    
    // 2秒后重置状态
    setTimeout(() => {
      justCopied.value = false
    }, 2000)
  } catch (error) {
    console.error('复制失败:', error)
    // 降级方案：使用传统方法复制
    try {
      const textarea = document.createElement('textarea')
      textarea.value = props.code
      document.body.appendChild(textarea)
      textarea.select()
      document.execCommand('copy')
      document.body.removeChild(textarea)
      justCopied.value = true
      setTimeout(() => { justCopied.value = false }, 2000)
    } catch (fallbackError) {
      console.error('降级复制也失败:', fallbackError)
    }
  } finally {
    isCopying.value = false
  }
}

// 运行代码功能
const runCode = async () => {
  if (isRunning.value) return
  
  isRunning.value = true
  
  try {
    emit('run-code', props.code, props.language)
    
    // 模拟运行延迟
    await new Promise(resolve => setTimeout(resolve, 500))
  } catch (error) {
    console.error('代码运行失败:', error)
  } finally {
    isRunning.value = false
  }
}

// 展开/收起功能
const toggleExpanded = () => {
  isExpanded.value = !isExpanded.value
}

// 生命周期
onMounted(async () => {
  await nextTick()
  
  // 确保Prism插件正常工作
  if (typeof Prism.highlightAll === 'function') {
    Prism.highlightAll()
  }
})
</script>

<style scoped>
/* 容器样式 */
.code-block-wrapper {
  margin: var(--space-lg) 0;
  border-radius: var(--radius-lg);
  overflow: hidden;
  border: 1px solid var(--border-light);
  background: var(--bg-card);
  box-shadow: var(--shadow-sm);
  transition: all var(--transition-fast);
}

.code-block-wrapper:hover {
  border-color: var(--color-primary-light);
  box-shadow: var(--shadow-md);
}

/* 头部样式 */
.code-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: var(--space-md) var(--space-lg);
  background: var(--bg-secondary);
  border-bottom: 1px solid var(--border-light);
}

.language-info {
  display: flex;
  align-items: center;
  gap: var(--space-md);
}

.language-badge {
  display: flex;
  align-items: center;
  gap: var(--space-sm);
  background: var(--color-primary-light);
  color: var(--color-primary);
  padding: var(--space-xs) var(--space-sm);
  border-radius: var(--radius-md);
  font-size: var(--font-size-sm);
  font-weight: var(--font-weight-medium);
  transition: all var(--transition-fast);
}

.language-badge.lang-html {
  background: var(--color-warning-light);
  color: var(--color-warning);
}

.language-badge.lang-css {
  background: var(--color-secondary-light);
  color: var(--color-secondary);
}

.language-badge.lang-javascript {
  background: #fff3cd;
  color: #856404;
}

.language-badge.lang-java {
  background: var(--color-accent-light);
  color: var(--color-accent);
}

.code-meta {
  display: flex;
  align-items: center;
  gap: var(--space-sm);
  font-size: var(--font-size-xs);
  color: var(--text-tertiary);
}

.line-count {
  background: var(--bg-tertiary);
  padding: 2px var(--space-xs);
  border-radius: var(--radius-sm);
}

/* 操作按钮 */
.code-actions {
  display: flex;
  gap: var(--space-sm);
}

.action-btn {
  display: flex;
  align-items: center;
  gap: var(--space-xs);
  padding: var(--space-sm) var(--space-md);
  border: none;
  border-radius: var(--radius-md);
  font-size: var(--font-size-sm);
  font-weight: var(--font-weight-medium);
  cursor: pointer;
  transition: all var(--transition-fast);
  background: var(--bg-tertiary);
  color: var(--text-secondary);
}

.action-btn:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: var(--shadow-sm);
}

.action-btn:active:not(:disabled) {
  transform: translateY(0);
}

.action-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.run-btn {
  background: var(--color-success-light);
  color: var(--color-success);
}

.run-btn:hover:not(:disabled) {
  background: var(--color-success);
  color: var(--text-inverse);
}

.copy-btn {
  background: var(--color-primary-light);
  color: var(--color-primary);
}

.copy-btn:hover:not(:disabled) {
  background: var(--color-primary);
  color: var(--text-inverse);
}

.expand-btn {
  background: var(--color-accent-light);
  color: var(--color-accent);
}

.expand-btn:hover:not(:disabled) {
  background: var(--color-accent);
  color: var(--text-inverse);
}

/* 代码内容区域 */
.code-content {
  position: relative;
  background: var(--bg-code);
}

.code-content.collapsible:not(.expanded) {
  max-height: 400px;
  overflow: hidden;
  position: relative;
}

.code-content.collapsible:not(.expanded)::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 60px;
  background: linear-gradient(transparent, var(--bg-code));
  pointer-events: none;
}

.code-pre {
  margin: 0;
  padding: var(--space-lg);
  font-family: var(--font-family-mono);
  font-size: var(--font-size-sm);
  line-height: var(--line-height-relaxed);
  overflow-x: auto;
  white-space: pre;
  color: var(--text-primary);
}

.code-pre.line-numbers {
  padding-left: 60px;
}

/* 行号样式 */
.line-numbers-container {
  position: absolute;
  top: 0;
  left: 0;
  padding: var(--space-lg) var(--space-sm);
  background: var(--bg-tertiary);
  border-right: 1px solid var(--border-light);
  font-family: var(--font-family-mono);
  font-size: var(--font-size-sm);
  line-height: var(--line-height-relaxed);
  color: var(--text-tertiary);
  user-select: none;
  display: flex;
  flex-direction: column;
  min-width: 40px;
}

.line-number {
  text-align: right;
  padding-right: var(--space-sm);
  transition: all var(--transition-fast);
}

.line-number.highlighted {
  background: var(--color-warning-light);
  color: var(--color-warning);
  font-weight: var(--font-weight-semibold);
}

/* 展开提示 */
.expand-hint {
  padding: var(--space-md);
  text-align: center;
  background: var(--bg-secondary);
  border-top: 1px solid var(--border-light);
}

.expand-hint-btn {
  background: none;
  border: none;
  color: var(--color-primary);
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: var(--space-sm);
  margin: 0 auto;
  padding: var(--space-sm) var(--space-md);
  border-radius: var(--radius-md);
  transition: all var(--transition-fast);
  font-size: var(--font-size-sm);
}

.expand-hint-btn:hover {
  background: var(--color-primary-light);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .code-header {
    flex-direction: column;
    gap: var(--space-md);
    align-items: flex-start;
  }
  
  .code-actions {
    width: 100%;
    justify-content: flex-end;
  }
  
  .action-btn {
    padding: var(--space-sm);
    font-size: var(--font-size-xs);
  }
  
  .action-btn span {
    display: none;
  }
  
  .code-pre {
    padding: var(--space-md);
    font-size: var(--font-size-xs);
  }
  
  .code-pre.line-numbers {
    padding-left: 50px;
  }
  
  .line-numbers-container {
    padding: var(--space-md) var(--space-xs);
    min-width: 35px;
    font-size: var(--font-size-xs);
  }
}

/* 代码主题样式 */
.code-block-wrapper :deep(.token.comment),
.code-block-wrapper :deep(.token.prolog),
.code-block-wrapper :deep(.token.doctype),
.code-block-wrapper :deep(.token.cdata) {
  color: #6a737d;
  font-style: italic;
}

.code-block-wrapper :deep(.token.keyword) {
  color: #d73a49;
  font-weight: var(--font-weight-semibold);
}

.code-block-wrapper :deep(.token.string),
.code-block-wrapper :deep(.token.attr-value) {
  color: #032f62;
}

.code-block-wrapper :deep(.token.number) {
  color: #005cc5;
}

.code-block-wrapper :deep(.token.function) {
  color: #6f42c1;
}

/* 暗色主题代码高亮 */
[data-theme="dark"] .code-block-wrapper :deep(.token.comment),
[data-theme="dark"] .code-block-wrapper :deep(.token.prolog),
[data-theme="dark"] .code-block-wrapper :deep(.token.doctype),
[data-theme="dark"] .code-block-wrapper :deep(.token.cdata) {
  color: #6a737d;
}

[data-theme="dark"] .code-block-wrapper :deep(.token.keyword) {
  color: #ff7b72;
}

[data-theme="dark"] .code-block-wrapper :deep(.token.string),
[data-theme="dark"] .code-block-wrapper :deep(.token.attr-value) {
  color: #a5d6ff;
}

[data-theme="dark"] .code-block-wrapper :deep(.token.number) {
  color: #79c0ff;
}

[data-theme="dark"] .code-block-wrapper :deep(.token.function) {
  color: #d2a8ff;
}
</style> 